package com.central.modules.security.controller;

import com.central.common.exception.BizExceptionEnum;
import com.central.common.exception.BusinessException;
import com.central.common.utils.Result;
import com.central.common.validator.ValidatorUtils;
import com.central.modules.security.dto.LoginDTO;
import com.central.modules.security.password.PasswordUtils;
import com.central.modules.security.service.CaptchaService;
import com.central.modules.security.service.SysUserTokenService;
import com.central.modules.security.user.SecurityUser;
import com.central.modules.security.user.UserDetail;
import com.central.modules.sys.entity.SysUserEntity;
import com.central.modules.sys.enums.UserStatusEnum;
import com.central.modules.sys.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * 登录管理
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/sys")
public class LoginController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private CaptchaService captchaService;

    //验证码
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response, @RequestParam String uuid) throws IOException {
        //生成验证码
        captchaService.create(response, uuid);
    }

    //登录
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginDTO login) {
        //效验数据
        ValidatorUtils.validateEntity(login);
        //验证码是否正确
        boolean flag = captchaService.validate(login.getUuid(), login.getCaptcha());
        if (!flag) {
            throw new BusinessException(BizExceptionEnum.CAPTCHA_ERROR);
        }

        //用户信息
        SysUserEntity user = sysUserService.getByUsername(login.getUsername());

        //用户不存在 //密码错误
        if (user == null || !PasswordUtils.matches(login.getPassword(), user.getPassword())) {
            throw new BusinessException(BizExceptionEnum.ACCOUNT_PASSWORD_ERROR);
        }

        //账号停用
        if (Objects.equals(user.getStatus(), Integer.valueOf(UserStatusEnum.DISABLE.getCode()))) {
            throw new BusinessException(BizExceptionEnum.ACCOUNT_DISABLE);
        }
        //登录成功
        Map<String, Object> map = sysUserTokenService.createToken(user.getId());
        return Result.succeed(map);
    }

    //退出
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        UserDetail user = SecurityUser.getUser();

        //退出
        sysUserTokenService.logout(user.getId());

        return Result.succeed(null);
    }

}